using System;
using System.Collections.Generic;

namespace Slobby.Server {
    class Program {
        static Net.ClientListener listener;
        static ClientAuthenticator authing;
        static ClientList clients;

        static Common.Dispatcher<ServerReciever> dispatch = new Slobby.Common.Dispatcher<ServerReciever>();

        static bool Running = true;

        static void RunningLoop() {
            while (Running) {
                int workerThreads, iocps;
                System.Threading.ThreadPool.GetAvailableThreads(out workerThreads, out iocps);
                Console.Clear();
                Console.WriteLine("Threads: {0} IOCP: {1}", workerThreads, iocps);
                System.Threading.Thread.Sleep(300000);
            }
        }

        static void Main(string[] args) {
            listener = new Net.ClientListener();
            listener.ClientConnected += NewConnection;

            clients = new ClientList();

            authing = new ClientAuthenticator(new Authentication.AuthenticationProvider());
            authing.ClientConnected += ClientAuthed;

            listener.BeginListen();

            RunningLoop();

            listener.EndListen();
            clients.DisconnectAll("Server is shutting down");
        }

        public static void Close() {
            
            Running = false;
        }

        static void ClientAuthed(Client obj) {

            ServerReciever r = new ServerReciever(obj, clients);
            obj.RecieveMessage += delegate(object msg) {
                dispatch.Dispatch(r, msg);
            };

            clients.Add(obj);
            obj.StartListening();
        }

        static void NewConnection(Net.ClientConnection client) {
            authing.Process(client);
        }
    }
}